package school.xauat.inscription_sys.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import school.xauat.inscription_sys.biz.BizCharactersService;
import school.xauat.inscription_sys.pojo.Characters;
import school.xauat.inscription_sys.pojo.User;
import school.xauat.inscription_sys.pojo.vo.RespVo;
import school.xauat.inscription_sys.service.CharactersService;
import school.xauat.inscription_sys.service.UserService;

import javax.servlet.http.HttpSession;
import javax.websocket.Session;

import static school.xauat.inscription_sys.errorcode.ErrorCode.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author zsy
 * @since 2022-04-26
 */
@RestController
@RequestMapping("/inscription_sys/characters")
public class CharactersController {

    @Autowired
    BizCharactersService bizCharactersService;

    @Autowired
    CharactersService charactersService;

    @Autowired
    UserService userService;

    @GetMapping("/{characters}/search")
    public RespVo search(@PathVariable() String characters, HttpSession session) {
        if (session.getAttribute("user") == null) {
            return RespVo.error(ERROR_NO_LOGIN, getMsg(ERROR_NO_LOGIN));
        }
        return bizCharactersService.searchByCharacters(characters);
    }

    @GetMapping("/{characters}/get")
    public RespVo get(@PathVariable() String characters) {
        return RespVo.obj(
                charactersService.getOne(
                        new QueryWrapper<Characters>().eq("name", characters)));
    }

    @GetMapping("/list")
    public RespVo list() {
        return RespVo.obj(charactersService.list());
    }

    @PostMapping("/add")
    public RespVo add(@RequestBody Characters characters, HttpSession session) {
        Object obj = session.getAttribute("user");
        if (obj == null) {
            return RespVo.error(ERROR_NO_LOGIN, getMsg(ERROR_NO_LOGIN));
        }
        User user = (User) obj;
        user = userService.getOne(new QueryWrapper<User>().eq("username", user.getUsername()));
        characters.setUserId(user.getId());
        if (charactersService.save(characters)) {
            return RespVo.ok();
        } else {
            return RespVo.error(ERROR_DB_UNKNOWN, getMsg(ERROR_DB_UNKNOWN));
        }
    }

}

